const router = require('koa-router')()
const topik = require('../model/topik');
const service = require('../service/topik')

router.get('/topikList', async (ctx, next) => {
    var { pageSize, count } = ctx.query;
    if (!pageSize) {
        pageSize = 10;
    }
    if (!count) {
        count = 1;
    }

    let list = await topik.find({}).limit(parseInt(pageSize)).skip(parseInt(count)).exec();

    await ctx.render('topik', {
        title: 'Topik',
        list: list
    })
})

router.get('/topik/:id', async (ctx, next) => {
    var id = ctx.params.id;
    var msg, data;

    if (id) {
        data = await topik.findById(id).exec();

        if (!data) {
            msg = '找不到数据'
        }
    } else {
        msg = '无效ID'
    }

    await ctx.render('topik-detail', {
        data: data,
        msg: msg,
        title: '详细'
    })
})

router.post('/topik/:id', async (ctx, next) => {
    console.log(ctx.params, ctx.query, ctx.request.body);

    var id = ctx.params.id;
    var msg, data;

    var { cn, ko, nature, note, newnote } = ctx.request.body;

    if (id) {

        if (cn && ko) {
            console.log(ctx.token);
            if (ctx.token) {
                data = service.put(ctx.token.id, {
                    id: id,
                    cn: cn,
                    ko: ko,
                    nature: nature,
                    note: note,
                    newnote: newnote
                })
            }
        }
        //data = await topik.findById(id);
    } else {
        msg = '无效ID'
    }

    ctx.response.redirect('/topik/' + id)

    /* await ctx.render('topik-detail', {
        data: data,
        msg: msg
    }) */
})

router.post('/topik', async (ctx, next) => {

    var msg, data;
    var { cn, ko, nature, note, newnote } = ctx.request.body;

    let one = await topik.findOne({ cn: cn, ko: ko });
    if (one) {
        msg = '已存在'
    } else {
        data = await new topik({
            cn: cn,
            ko: ko,
            nature: nature,
            note: note,
            newnote: newnote
        }).save();
    }
    ctx.response.redirect('/topikList')
})

router.get('/topik', async (ctx, next) => {
    await ctx.render('topik-detail', {
        data: {},
        msg: undefined,
        title: '添加'
    })
})

module.exports = router